// pages/shopcart/settlement/settlement.js
const app = getApp()
var help = require('../../../utils/help.js');
var login = require('../../../utils/login.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coupon_list: [],
    index0: 0,
    coupon_data: {},
    cart_ids:'',
    data: [],
    address: [],
    total: 0,
    total_show: 0,
    yingxiao_s:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.cart_ids) {
      this.setData({
        cart_ids: options.cart_ids
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadData(true)
  },

  jian: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        break;
      }
    }
    if (showGoodsData.num > 1) {
      help.get(app.data.apiUrl + 'Goods/addCard', {
        token: app.data.userInfo ? app.data.userInfo.token : '',
        goods_id: showGoodsData.goods_info.id,
        num: showGoodsData.num - 1
      }, that, function (res, that) {
        var result = res.data;
        // console.log(result);
        if (result.code == 1) {
          that.loadData(true)
        } else {
          help.msg(result.msg)
        }

      });
    }
  },
  jia: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        break;
      }
    }
    if (showGoodsData.num < showGoodsData.goods_info.kucun) {
      help.get(app.data.apiUrl + 'Goods/addCard', {
        token: app.data.userInfo ? app.data.userInfo.token : '',
        goods_id: showGoodsData.goods_info.id,
        num: showGoodsData.num + 1
      }, that, function (res, that) {
        var result = res.data;
        // console.log(result);
        if (result.code == 1) {
          that.loadData(true)
        } else {
          help.msg(result.msg)
        }

      });
    }
  },
  set_num: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var i = 0;
    var showGoodsData = {};
    for (i in that.data.data) {
      if (that.data.data[i].id == id) {
        showGoodsData = that.data.data[i];
        break;
      }
    }
    var num = e.detail.value;
    if (num <= 0) {
      num = 1;
    } else if (num >= showGoodsData.goods_info.kucun) {
      num = showGoodsData.goods_info.kucun;
    }
    if (num > 0 && num !== '') {
      help.get(app.data.apiUrl + 'Goods/addCard', {
        token: app.data.userInfo ? app.data.userInfo.token : '',
        goods_id: showGoodsData.goods_info.id,
        num: num
      }, that, function (res, that) {
        var result = res.data;
        // console.log(result);
        if (result.code == 1) {
          that.loadData(true)
        } else {
          help.msg(result.msg)
        }

      });
    }

  },

  /**
   * 加载数据
   */
  loadData: function (is_one) {
    var that = this;

    if (is_one === true) {
      that.setData({
        is_load: true
      })
    }
    if (this.data.load_lock || !this.data.is_load) {
      return false;
    }
    this.setData({
      load_lock: true,
      load_ts: '正在加载'
    })
    if (is_one === true) {
      that.setData({
        page: 1,
        data: []
      })
    }

    var url = app.data.apiUrl + 'Order/add';
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      keyword: that.data.keyword,
      page: that.data.page,
      cart_ids: that.data.cart_ids
    };
    help.get(url, data, that, function (res, that) {
      that.setData({
        load_lock: false
      })
      var result = res.data;
      console.log(result);
      if (result.code == 1) {
          if (is_one === true) {
            var new_data = result.data.data;
          } else {
            var new_data = that.data.data.concat(result.data.data)
          }
          console.log(new_data)
          that.setData({
            data: new_data,
            total: result.data.total,
            total_show: result.data.total,
            total_show: result.data.total > that.data.coupon_data.val ? result.data.total - that.data.coupon_data.val : result.data.total,
            load_ts: '',
            address: result.data.address,
            yingxiao_s: result.data.yingxiao_s,
            coupon_list: result.data.coupon_list,
          })
        that.data.page++;

      } else if (result.code == 401) {
        help.msg('登录已失效，正在重新登录...')
        // 重新检测登录状态
        login.getUserInfo(app);
        return false;
      } else {
        help.msg(result.msg)
        return false;
      }

    });
  },

  bindPickerChange22: function (e) {
    console.log(e)
    var coupon_data = [];
    var i = 0;
    for (i in this.data.coupon_list) {
      if (i == e.detail.value) {
        coupon_data = this.data.coupon_list[i];
      }
    }
    this.setData({
      index0: e.detail.value,
      coupon_data: coupon_data,
      total_show: this.data.total > coupon_data.val ? this.data.total - coupon_data.val : this.data.total
    })
  },

  /**
     * 下单
     */
  buy: function (e) {
    var that = this;
    var url = app.data.apiUrl + 'Order/apply_sub';
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      cart_ids: that.data.cart_ids,
      coupon_id: that.data.index0 > 0 ? that.data.coupon_data.id : 0,
    };
    help.get(url, data, that, function (res, that) {
      var result = res.data;
      // console.log(result);
      if (result.code == 1) {
        that.goPay(result.data.pay_id);
      } else {
        help.msg(result.msg)
        return false;
      }

    });
  },
  /**
   * 微信支付
   */
  goPay: function (pay_id) {
    var that = this;
    var url = app.data.apiUrl + '/Order/wxpay';
    wx.showLoading({
      title: '正在加载...',
    })
    var data = {
      token: app.data.userInfo ? app.data.userInfo.token : '',
      pay_id: pay_id,
    };
    help.get(url, data, that, function (res, that) {
      wx.hideLoading()
      var result = res.data;
      console.log(result);
      if (result.code == 1) {
        var url = '/pages/order/order';
        // help.goUrl(url);
        wx.requestPayment({
          'timeStamp': result.data.timeStamp,
          'nonceStr': result.data.nonceStr,
          'package': result.data.package,
          'signType': result.data.signType,
          'paySign': result.data.paySign,
          'success': function (res) {
            console.log(res)
            help.msg('支付成功');
            setTimeout(function () {
              var url = '/pages/order/order';
              help.goUrlClose(url);
            }, 1000)
          },
          fail: function (res) {
            console.log(res)
            if (res && res.errMsg == 'requestPayment:fail cancel') {
              help.msg('未完成支付')
            } else {
              help.msg('支付失败！' + (res ? res.errMsg : ''))
            }

          }
        })

      } else if (result.code == 1) {
        help.msg('登录已失效，正在重新登录...')
        // 重新检测登录状态
        login.getUserInfo(app);
      } else {
        help.msg(result.msg)
        return false;
      }


    }, function (res, that) {
      wx.hideLoading()
      console.log(res);
      help.msg('网络异常！')
    });

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})